<template>
  <div class="app-container"> <el-row :gutter="20"> 
    <!-- 左侧培训列表 --> 
    <el-col :span="0">
        <!-- <div class="training-list-container">
          <div class="training-search"> <el-input v-model="trainingQuery" placeholder="搜索培训名称" clearable
              @input="searchTrainings"> <template #prefix> <i class="el-input__icon el-icon-search"></i> </template>
            </el-input> </div>
          <div class="training-list"> <el-scrollbar height="600px"> <el-menu :default-active="selectedTrainingId"
                class="training-menu"> <el-menu-item v-for="training in filteredTrainings" :key="training.trainingId"
                  :index="training.trainingId.toString()" @click="handleTrainingSelect(training)">
                  <span>{{ training.trainingName || '未命名培训' }}</span> </el-menu-item> </el-menu> </el-scrollbar> </div>
          <div class="training-summary" align="right">
            <el-tag type="primary" effect="dark">
              总计： {{ filteredTrainings.length }} 条
            </el-tag>
          </div>
        </div> -->
      </el-col>

      <!-- 右侧订餐详情 -->
      <el-col :span="24">
        <!-- 搜索框 -->
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
          <!-- 时间选择控件（年月） -->
          <el-form-item label="时间" prop="trainingDate">
            <el-date-picker
              v-model="queryParams.trainingMonth"
              type="month"
              placeholder="请选择年月"
              format="YYYY-MM"
              value-format="YYYY-MM"
              clearable
              @change="handleQuery"
            />
          </el-form-item>
          <el-form-item label="培训名称" prop="employeeName">
              <el-select 
                v-model="queryParams.trainingId" 
                placeholder="请选择培训名称" 
                clearable 
                @change="handleQuery"
              >
                <el-option 
                  v-for="training in (queryParams.trainingMonth && monthlyTrainings.length >= 0 ? monthlyTrainings : trainings)" 
                  :key="training.trainingId" 
                  :label="training.trainingName" 
                  :value="training.trainingId" 
                />
              </el-select>
            </el-form-item>

          <el-form-item label="员工姓名" prop="employeeName">
            <el-input v-model="queryParams.employeeName" placeholder="请输入员工姓名" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="电话" prop="phone">
            <el-input v-model="queryParams.phone" placeholder="请输入员工电话" clearable @keyup.enter="handleQuery" />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-card class="training-info-card" v-if="selectedTraining" shadow="hover">
          <template #header>
            <div class="training-info-header">
              <i-ep-collection class="header-icon" />
              <div class="header-content">
                <div class="header-title">
                  {{ selectedTraining.trainingName || '未命名培训' }}
                  <span v-if="selectedTraining.startDate || selectedTraining.endDate" class="header-time"
                    style="font-size: 12px;">
                    <i-ep-timer class="time-icon" />
                    <span v-if="selectedTraining.startDate && selectedTraining.endDate" style="font-size: 12px;">
                      {{ parseTime(selectedTraining.startDate, '{y}/{m}/{d}') }} - {{
                        parseTime(selectedTraining.endDate, '{y}/{m}/{d}') }}
                    </span>
                    <span v-else-if="selectedTraining.startDate" style="font-size: 12px;">
                      {{ parseTime(selectedTraining.startDate, '{y}/{m}/{d}') }} 开始
                    </span>
                    <span v-else-if="selectedTraining.endDate" style="font-size: 12px;">
                      至 {{ parseTime(selectedTraining.endDate, '{y}/{m}/{d}') }}
                    </span>
                  </span>
                </div>
              </div>
            </div>
          </template>

          <!-- 培训信息显示 -->
          <el-descriptions :column="3" border size="small" style="width: 50%;">

            <el-descriptions-item label="培训负责人" width="100px" align="center">
              <div class="manager-info">
                <el-tag size="small" type="primary">
                  {{ selectedTraining.manager || '暂无' }}
                </el-tag>
              </div>
            </el-descriptions-item>
            <el-descriptions-item label="电子邮箱" width="100px" align="center">
              <el-tag size="small" v-if="selectedTraining.email" align="left">{{ selectedTraining.email }}</el-tag>
              <el-tag type="info" size="small" v-else>暂无</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="联系电话" width="100px" align="center">
              <el-tag size="small" v-if="selectedTraining.phone">{{ selectedTraining.phone }}</el-tag>
              <el-tag type="info" size="small" v-else>暂无</el-tag>
            </el-descriptions-item>
          </el-descriptions>
        </el-card>
        <!-- 搜索框 -->
        <!-- <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="员工姓名" prop="employeeName">
            <el-input v-model="queryParams.employeeName" placeholder="请输入员工姓名" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="电话" prop="phone">
            <el-input v-model="queryParams.phone" placeholder="请输入员工电话" clearable @keyup.enter="handleQuery" />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form> -->

        <el-row :gutter="10" class="mb8">
          <!-- <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['mealorder:order:add']"
              :disabled="!selectedTrainingId">新增</el-button>
          </el-col> -->
          <!-- 
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
              v-hasPermi="['mealorder:order:edit']">修改</el-button>
          </el-col>
          -->
          <el-button type="danger" plain icon="Delete" :disabled="hasNoSelection" @click="handleDelete()"
              v-hasPermi="['mealorder:order:remove']">删除</el-button>
          <el-col :span="1.5">
            <el-button type="info" plain icon="Upload" @click="handleImport"
              v-hasPermi="['mealorder:order:import']">导入</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport"
              v-hasPermi="['mealorder:order:export']" :disabled="!selectedTrainingId">导出</el-button>
          </el-col>
          <!-- 发送邮件按钮 -->
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Message" @click="handleSendEmail"
              :disabled="!selectedTrainingId">邮件提醒</el-button>
          </el-col>

          <el-col :span="1.5">
            <el-button type="info" plain :icon="showEmployeeDetails ? 'Hide' : 'View'" @click="toggleEmployeeDetails">
              {{ showEmployeeDetails ? '隐藏员工信息详情' : '显示员工信息详情' }}
            </el-button>
          </el-col>
          <!-- 添加显示未订餐人员按钮 -->
          <!-- <el-col :span="1.5">
            <el-button type="warning" plain icon="User" @click="showUnorderedEmployees">
              {{ isUnorderedFilterActive ? '显示所有人员' : '显示未订餐人员' }}
            </el-button>
          </el-col> -->

          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>


        </el-row>

        <!-- 表格区域 - 添加展开列功能 -->
        <el-table v-loading="loading" :data="paginatedData" @selection-change="handleSelectionChange"
          style="width: 100%" :scroll="{}">
          <el-table-column type="selection" width="30" align="center" />
          <el-table-column label="序号" align="center" width="60">
            <template #default="scope">
              {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
            </template>
          </el-table-column>

          <!-- 员工姓名列 -->
          <el-table-column label="姓名" align="center" prop="employeeName" width="70" />

          <!-- 可隐藏的员工详细信息列 -->
          <el-table-column label="员工编号" align="center" prop="employeeNo" v-if="showEmployeeDetails" width="100" />
          <!-- 修改性别列的显示方式 -->
          <el-table-column label="性别" align="center" v-if="showEmployeeDetails" width="55">
            <template #default="scope">
              <span>{{ scope.row.sex === '1' || scope.row.sex === 1 ? '男' : '女' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="部门" align="center" prop="dept" v-if="showEmployeeDetails" width="80" />
          <el-table-column label="手机号码" align="center" prop="phone" v-if="showEmployeeDetails" width="120" />
          <el-table-column label="邮箱" align="center" prop="email" v-if="showEmployeeDetails" width="180" />

          <!--重点修改部分！！！！！！！！！！！！！！！！！！！！！！！！！1-->>
          <template v-if="dateColumns.length > 0">
            <template v-for="dateCol in dateColumns" :key="dateCol.date">
              <el-table-column :label="dateCol.label" align="center" :width="180">
                <el-table-column :prop="dateCol.lunchProp" label="午餐" align="center" width="90">
                  <template #default="scope">
                    <el-tag :type="getOrderStatusType(scope.row[dateCol.lunchProp])" class="no-ellipsis">
                      {{ getOrderStatusText(scope.row[dateCol.lunchProp]) }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column :prop="dateCol.dinnerProp" label="晚餐" align="center" width="90">
                  <template #default="scope">
                    <el-tag :type="getOrderStatusType(scope.row[dateCol.dinnerProp])" class="no-ellipsis">
                      {{ getOrderStatusText(scope.row[dateCol.dinnerProp]) }}
                    </el-tag>
                  </template>
                </el-table-column>
              </el-table-column>
            </template>
          </template>

          
          
          
          
          <template v-else>
            <el-table-column label="用餐情况" align="center">
              <template #default="scope">
                <span>暂无用餐数据</span>
              </template>
            </el-table-column>
          </template>

          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
            <template #default="scope">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                v-hasPermi="['mealorder:order:edit']">修改</el-button>

              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                v-hasPermi="['mealorder:order:remove']">删除</el-button>
            </template>
          </el-table-column>
        </el-table>


        <pagination v-show="total > 0" :total="total" v-model:page="currentPage" v-model:limit="pageSize"
          @pagination="handlePagination" />
      </el-col>
    </el-row>

     <!-- 在 </el-dialog> 后面添加导入对话框 -->
    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
        :action="upload.url" :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" 
        :on-error="handleFileError" :auto-upload="false" drag
        :on-change="handleFileChange" :file-list="fileList">
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <div class="el-upload__tip">
              <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的订餐数据
            </div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
              @click="importTemplate">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

 <!-- 邮件发送对话框 -->
    <el-dialog :title="emailDialog.title" v-model="emailDialog.open" width="600px" append-to-body>
      <el-form ref="emailRef" :model="emailForm" :rules="emailRules" label-width="100px">
        <el-form-item label="收件人" prop="to">
          <el-input v-model="emailForm.to" type="textarea" :rows="4" placeholder="请输入收件人邮箱，多个邮箱用分号分隔" />
          <div style="margin-top: 5px; font-size: 12px; color: #999;">
            已筛选出 {{ emailRecipients.length }} 位未填写订餐信息的用户
          </div>
        </el-form-item>
        <el-form-item label="邮件主题" prop="subject">
          <el-input v-model="emailForm.subject" placeholder="请输入邮件主题" />
        </el-form-item>
        <el-form-item label="邮件内容" prop="content">
          <el-input v-model="emailForm.content" type="textarea" :rows="6" placeholder="请输入邮件内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitEmailForm" :loading="emailDialog.sending">发送邮件</el-button>
          <el-button @click="cancelEmail">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加或修改订餐管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="orderRef" :model="form" :rules="rules" label-width="80px">



        <!-- 添加员工相关信息 -->
        <!-- 添加员工相关信息 -->
        <!-- 修改表单部分，根据新增或修改状态显示不同的字段 -->
        <!-- 添加员工相关信息 -->
        <!-- 修改表单部分，添加失去焦点事件 -->
        <el-form-item label="员工姓名" prop="employeeName">
          <el-input v-model="form.employeeName" placeholder="请输入员工姓名"
            :disabled="form.id !== null && form.id !== undefined" @blur="validateEmployeeOnBlur" />
        </el-form-item>

        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号码" :disabled="form.id !== null && form.id !== undefined"
            @blur="validateEmployeeOnBlur" />
        </el-form-item>

        <!-- 只在修改时显示部门和邮箱 -->
        <el-form-item label="部门" prop="deptName" v-if="form.id !== null && form.id !== undefined">
          <el-select v-model="form.dept" placeholder="请选择部门" clearable
            :disabled="form.id !== null && form.id !== undefined">
            <el-option v-for="dict in deptOptions" :key="dict.deptId" :label="dict.deptName" :value="dict.deptName" />
          </el-select>
        </el-form-item>

        <el-form-item label="邮箱" prop="email" v-if="form.id !== null && form.id !== undefined">
          <el-input v-model="form.email" placeholder="请输入邮箱" :disabled="form.id !== null && form.id !== undefined" />
        </el-form-item>

        <el-form-item v-if="selectedTraining && selectedTraining.startDate && selectedTraining.endDate" label="培训时间">
          <el-tag type="primary">{{ parseTime(selectedTraining.startDate, '{y}/{m}/{d}') }} - {{
            parseTime(selectedTraining.endDate, '{y}/{m}/{d}') }}</el-tag>
        </el-form-item>

        <el-form-item label="订餐详情">
          <el-table :data="mealDetailData" border size="small">
            <el-table-column label="日期" align="center" style="width: auto;">
              <template #default="scope">
                <!-- 显示日期 -->
                {{ scope.row.dateLabel }}
              </template>
            </el-table-column>
            <el-table-column label="午餐" align="center" width="140">
              <template #default="scope">
                <div>
                  <el-select v-model="scope.row.lunch" placeholder="请选择" style="width: 100%;">
                    <el-option label="未填写" value="3"></el-option>
                    <el-option label="核销" value="2"></el-option>
                    <el-option label="已订" value="1"></el-option>
                    <el-option label="不订" value="0"></el-option>
                  </el-select>
                </div>
              </template>
            </el-table-column>

            <el-table-column label="晚餐" align="center" width="140">
              <template #default="scope">
                <div>
                  <el-select v-model="scope.row.dinner" placeholder="请选择" style="width: 100%;">
                    <el-option label="未填写" value="3"></el-option>
                    <el-option label="核销" value="2"></el-option>
                    <el-option label="已订" value="1"></el-option>
                    <el-option label="不订" value="0"></el-option>
                  </el-select>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Order">
import { listOrder, getOrder, delOrder, exportOrder,addOrder, updateOrder, voList, delOrdersByEmpAndTraining, importTemplate as downloadImportTemplate ,
    sendEmail,
  sendCustomEmail,
  alterMealStatus,
  importData, // 添加导入方法
  importMealOrderTable 
} from "@/api/mealorder/order"
import { listTrainings } from "@/api/training/training"
import { getToken } from "@/utils/auth"
import { listDept } from "@/api/system/dept"
import { validateEmployee } from "@/api/employeeManagement/employeeManagement"
import { getTrainingsByYearAndMonth } from "@/api/training/training"

// 添加用于存储按月份筛选的培训数据的响应式变量
const monthlyTrainings = ref([])

const { proxy } = getCurrentInstance()
const sys_dept_list = ref([])
// 添加处理后的数据列表
const processedData = ref([])
const processedOrderList = ref([])
const orderList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
// 控制员工详情列的显示
const showEmployeeDetails = ref(false)
// 动态日期列
const dateColumns = ref([])
// 前端分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const paginatedData = ref([])

const upload = reactive({
  open: false,
  title: "",
  isUploading: false,
  updateSupport: true, // 默认值改为 true
  headers: { Authorization: "Bearer " + getToken() },
  url: import.meta.env.VITE_APP_BASE_API + "/mealorder/order/importMealOrderTable" // 修改为新的接口地址
})

// 添加邮件相关的ref和数据
const emailDialog = reactive({
  open: false,
  title: "",
  sending: false
})

const emailForm = reactive({
  to: "",
  subject: "",
  content: ""
})

const emailRules = {
  to: [
    { required: true, message: "收件人不能为空", trigger: "blur" }
  ],
  subject: [
    { required: true, message: "邮件主题不能为空", trigger: "blur" }
  ],
  content: [
    { required: true, message: "邮件内容不能为空", trigger: "blur" }
  ]
}

// 存储未填写订餐信息的用户邮箱
const emailRecipients = ref([])

const fileList = ref([]) // 添加文件列表

// 添加处理文件变化的方法
function handleFileChange(file, fileList) {
  // 限制只能上传一个文件
  if (fileList.length > 1) {
    fileList.splice(0, 1)
  }
  // 更新文件列表
  fileList.value = fileList
}

// 添加处理文件上传错误的方法
function handleFileError(error, file, fileList) {
  upload.isUploading = false
  proxy.$modal.msgError("文件上传失败: " + (error.message || ""))
}


// 添加发送邮件相关方法
function handleSendEmail() {
  // 获取未填写订餐信息的用户
  getEmailRecipients()
  emailDialog.title = "发送邮件提醒"
  emailDialog.open = true
  emailDialog.sending = false

  // 设置默认邮件主题和内容
  emailForm.subject = `【提醒】请填写${selectedTraining.value?.trainingName || '培训'}期间的订餐信息`
  // emailForm.content = `您好！\n\n您参加的"${selectedTraining.value?.trainingName || '培训'}"（${selectedTraining.value?.startDate ? parseTime(selectedTraining.value.startDate, '{y}-{m}-{d}') : ''}${selectedTraining.value?.endDate ? '至' + parseTime(selectedTraining.value.endDate, '{y}-{m}-{d}') : ''}）期间的订餐信息尚未填写。\n\n请及时登录系统填写订餐信息，以便我们为您安排用餐。\n\n谢谢配合！`
  // emailForm.content = `您好!`
}

// 获取未填写订餐信息的用户邮箱
function getEmailRecipients() {
  emailRecipients.value = []
  const recipients = []

  // 遍历当前页面数据，查找未填写订餐信息的用户
  paginatedData.value.forEach(item => {
    // 检查是否有未填写的订餐信息
    let hasUnfilled = false

    // 检查每个日期列的午餐和晚餐状态
    dateColumns.value.forEach(col => {
      // 如果午餐或晚餐状态为3或null/undefined（未填写），则标记为有未填写项
      const lunchStatus = item[col.lunchProp];
      const dinnerStatus = item[col.dinnerProp];
      
      if (lunchStatus === 3 || lunchStatus === '3' || lunchStatus === null || lunchStatus === undefined ||
          dinnerStatus === 3 || dinnerStatus === '3' || dinnerStatus === null || dinnerStatus === undefined) {
        hasUnfilled = true
      }
    })

    // 如果有未填写项且用户邮箱存在，则添加到收件人列表
    if (hasUnfilled && item.email) {
      recipients.push({
        email: item.email,
        name: item.employeeName,
        employeeNo: item.employeeNo
      })
    }
  })

  emailRecipients.value = recipients
  // 将邮箱地址拼接成字符串
  emailForm.to = recipients.map(r => r.email).join(';')
}

// 提交邮件表单
function submitEmailForm() {
  proxy.$refs["emailRef"].validate(valid => {
    if (valid) {
      emailDialog.sending = true

      // 构造发送给后端的数据对象
      const emailData = {
        to: emailForm.to,
        subject: emailForm.subject,
        content: emailForm.content
      }

      // 调用发送邮件的API
      sendCustomEmail(emailData).then(response => {
        emailDialog.sending = false
        if (response.code === 200) {
          proxy.$modal.msgSuccess("邮件发送成功")
          emailDialog.open = false
        } else {
          proxy.$modal.msgError("邮件发送失败: " + response.msg)
        }
      }).catch(error => {
        emailDialog.sending = false
        proxy.$modal.msgError("邮件发送失败: " + (error.message || ""))
      })
    }
  })
}



// 取消发送邮件
function cancelEmail() {
  emailDialog.open = false
  resetEmailForm()
}

// 重置邮件表单
function resetEmailForm() {
  emailForm.to = ""
  emailForm.subject = ""
  emailForm.content = ""
  proxy.resetForm("emailRef")
}


const mealDetailData = ref([])
// 培训相关数据
const trainings = ref([])
const trainingQuery = ref('')
const selectedTrainingId = ref(null)
const selectedTraining = ref(null)
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    trainingId: null,
    empId: null,
    trainingDateRange: null, // 日期区间
    startDate: null, // 开始日期
    endDate: null,   // 结束日期
    mealType: null,
    isOrdered: null,
    employeeName: null,
    phone: null
  },
  rules: {
    employeeName: [
      { required: true, message: "员工姓名不能为空", trigger: "blur" }
    ],
    employeeNo: [
      { required: true, message: "员工编号不能为空", trigger: "blur" }
    ],
    sex: [
      { required: true, message: "性别不能为空", trigger: "change" }
    ],
    dept: [  // 这里保持为 dept，因为这是表单验证规则
      { required: true, message: "部门不能为空", trigger: "blur" }
    ],
    phone: [
      { required: true, message: "手机号码不能为空", trigger: "blur" },
      { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号码", trigger: "blur" }
    ],
    email: [
      { required: true, message: "邮箱不能为空", trigger: "blur" },
      { type: "email", message: "请输入正确的邮箱地址", trigger: "blur" }
    ]
  }
})

const isUnorderedFilterActive = ref(false)
// 添加显示未订餐人员的方法
function showUnorderedEmployees() {
  if (!selectedTrainingId.value) {
    proxy.$modal.msgWarning("请先选择一个培训");
    return;
  }

  // 切换筛选状态
  isUnorderedFilterActive.value = !isUnorderedFilterActive.value;
  
  if (isUnorderedFilterActive.value) {
    // 设置查询参数，筛选未订餐人员
    queryParams.value.hasUnordered = '0'; // 标记为查询未完全订餐的员工
    proxy.$modal.msgSuccess("已筛选出未完全订餐的员工");
  } else {
    // 清除筛选参数，显示所有人员
    queryParams.value.hasUnordered = null;
    proxy.$modal.msgSuccess("已显示所有人员");
  }

  // 重新加载数据
  getList();
}

const { queryParams, form, rules } = toRefs(data)
const deptOptions = ref([])
// 切换员工详情列的显示状态
const toggleEmployeeDetails = () => {
  showEmployeeDetails.value = !showEmployeeDetails.value
}

// 计算属性 - 过滤后的培训列表
const filteredTrainings = computed(() => {
  if (!trainingQuery.value) {
    return trainings.value
  }
  return trainings.value.filter(training =>
    (training.trainingName || '未命名培训').includes(trainingQuery.value)
  )
})

// 获取培训列表
const getTrainings = async () => {
  try {
    const response = await listTrainings({ pageSize: 999999 })
    console.log('培训列表响应数据:', response)

    // 确保数据格式正确
    const data = response.data?.rows || response.data || response.rows || []

    if (!Array.isArray(data)) {
      console.warn('培训列表数据格式异常，期望为数组，实际类型:', typeof data)
      trainings.value = []
      return
    }

    // 去重：使用 Map 以 trainingId 为键
    const uniqueTrainings = new Map()
    data.forEach(item => {
      // 确保 trainingId 存在
      const trainingId = item.trainingId || item.id
      const trainingName = item.trainingName || item.name || '未命名培训'

      if (trainingId) {
        uniqueTrainings.set(trainingId, {
          ...item,
          trainingId: trainingId,
          trainingName: trainingName
        })
      }
    })

    trainings.value = Array.from(uniqueTrainings.values())
    console.log('处理后的培训列表:', trainings.value)

    // 页面加载时默认选择第一个培训
    if (trainings.value.length > 0) {
      // 使用 nextTick 确保 DOM 更新后再执行选择操作
      nextTick(() => {
        // 直接调用选择第一个培训的逻辑
        const firstTraining = trainings.value[0];
        selectedTrainingId.value = firstTraining.trainingId.toString();
        queryParams.value.trainingId = firstTraining.trainingId;
        selectedTraining.value = firstTraining;
        
        // 触发查询
        handleQuery();
      });
    } else {
      // 如果没有培训数据，清空相关状态
      selectedTrainingId.value = null;
      queryParams.value.trainingId = null;
      selectedTraining.value = null;
    }
  } catch (error) {
    console.error('获取培训列表失败:', error)
    proxy.$modal.msgError('获取培训列表失败，请检查网络或联系管理员')
    trainings.value = []
    
    // 出错时也清空相关状态
    selectedTrainingId.value = null;
    queryParams.value.trainingId = null;
    selectedTraining.value = null;
  }
}

// 搜索培训
const searchTrainings = () => {
  // 这里使用计算属性 filteredTrainings 来过滤
}

// 选择培训
const handleTrainingSelect = (training) => {
  console.log('选择的培训:', training)
  selectedTrainingId.value = training.trainingId.toString()
  queryParams.value.trainingId = training.trainingId  // 设置培训ID
  selectedTraining.value = training
  
  // 重置未订餐筛选状态
  isUnorderedFilterActive.value = false
  queryParams.value.hasUnordered = null
  
  handleQuery()  // 触发查询
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 修改表单重置函数
function reset() {
  form.value = {
    id: null,
    trainingName: null,
    trainingDateRange: null,
    employeeName: null,
    employeeNo: null,
    sex: null,
    dept: null,  // 保持为 dept
    phone: null,
    email: null,
    mealDate: null,
    mealType: null,
    isOrdered: null
  }
  proxy.resetForm("orderRef")
  mealDetailData.value = []
}

// 修改时间选择控件的处理函数
function handleQuery() {
  queryParams.value.pageNum = 1
  currentPage.value = 1
  
  // 如果选择了年月，则获取该月份的培训数据
  if (queryParams.value.trainingMonth) {
    getTrainingsByMonth(queryParams.value.trainingMonth)
  } else {
    // 如果清空了年月选择，重置为显示所有培训
    monthlyTrainings.value = []
    // 注意：不清空已选择的培训，除非明确需要
  }
  
  // 如果培训ID发生变化，更新selectedTraining和mealDetailData
  if (queryParams.value.trainingId) {
    // 查找培训信息时优先从monthlyTrainings查找，如果没有则从trainings查找
    const training = (monthlyTrainings.value.length > 0 ? monthlyTrainings.value : trainings.value)
      .find(t => t.trainingId == queryParams.value.trainingId)
    if (training) {
      selectedTraining.value = training
      
      // 如果是新增模式且对话框已打开，更新订餐详情日期
      if (open.value && !form.value.id) {
        generateMealDetailData(training.startDate, training.endDate)
      }
    }
  }
  
  if (queryParams.value.trainingDateRange && queryParams.value.trainingDateRange.length === 2) {
    queryParams.value.startDate = queryParams.value.trainingDateRange[0]
    queryParams.value.endDate = queryParams.value.trainingDateRange[1]
  } else {
    queryParams.value.startDate = null
    queryParams.value.endDate = null
  }

  // 检查是否处于未订餐人员筛选模式，并且有搜索条件
  if (queryParams.value.hasUnordered === '0' && queryParams.value.employeeName) {
    checkOrderedEmployeeInSearch();
  }

  getList()
}

// 新增函数：根据年月获取培训数据
function getTrainingsByMonth(yearMonth) {
  if (!yearMonth) {
    // 如果没有选择年月，重置为显示所有培训
    monthlyTrainings.value = []
    return
  }
  
  // 调用接口获取指定年月的培训数据
  getTrainingsByYearAndMonth(yearMonth).then(response => {
    if (response.code === 200) {
      // 处理返回的数据，格式化为与trainings相同结构
      const data = response.data || []
      monthlyTrainings.value = data.map(item => ({
        ...item,
        trainingId: item.id,
        trainingName: item.trainingName
      }))
      
      // 如果当前选择的培训不在新列表中，清空选择
      if (queryParams.value.trainingId) {
        const exists = monthlyTrainings.value.some(t => t.trainingId == queryParams.value.trainingId)
        if (!exists) {
          queryParams.value.trainingId = null
          selectedTraining.value = null
        }
      }
    } else {
      proxy.$modal.msgError("获取培训数据失败: " + response.msg)
      monthlyTrainings.value = []
    }
  }).catch(error => {
    console.error('获取培训数据失败:', error)
    proxy.$modal.msgError("获取培训数据失败: " + (error.message || ''))
    monthlyTrainings.value = []
  })
}

// 检查搜索的员工是否在已订餐名单中
function checkOrderedEmployeeInSearch() {
  // 只在未订餐筛选模式下检查
  if (queryParams.value.hasUnordered === '0' && queryParams.value.employeeName) {
    const searchName = queryParams.value.employeeName.trim();

    // 如果当前显示的数据为空，但用户仍在未订餐筛选模式下搜索，说明搜索的员工可能已订餐
    if (searchName && processedData.value.length === 0) {
      // 获取所有员工数据（包括已订餐和未订餐）来检查
      const allParams = {
        ...queryParams.value,
        hasUnordered: null,
        trainingId: queryParams.value.trainingId,
        employeeName: searchName
      };

      voList(allParams).then(response => {
        if (response.rows && response.rows.length > 0) {
          // 提示用户搜索的员工已在订餐名单中
          proxy.$modal.msgWarning(`您当前在未订餐人员中搜索，但该员工已在订餐名单中`);
        }
      }).catch(() => {
        // 忽略错误
      });
    } else if (searchName) {
      // 检查搜索的员工是否在当前已订餐名单中
      const allParams = {
        ...queryParams.value,
        hasUnordered: null,
        trainingId: queryParams.value.trainingId,
        employeeName: searchName
      };

      voList(allParams).then(response => {
        if (response.rows && response.rows.length > 0) {
          // 检查当前未订餐列表中是否包含搜索的员工
          const foundInUnordered = processedData.value.some(item =>
            item.employeeName && item.employeeName.includes(searchName)
          );

          if (!foundInUnordered && response.rows.length > 0) {
            // 提示用户搜索的员工已在订餐名单中
            proxy.$modal.msgWarning(`您当前在未订餐人员中搜索，但员工"${searchName}"已在订餐名单中`);
          }
        }
      }).catch(() => {
        // 忽略错误
      });
    }
  }
}
function handleUpdateWithLog(row) {
  console.log('=== 点击修改按钮 ===')
  console.log('传入的行数据:', row)
  handleUpdate(row)
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  // 重置日期区间
  queryParams.value.employeeName = null
  queryParams.value.phone = null
  // 重置日期区间
  queryParams.value.trainingDateRange = null
  queryParams.value.startDate = null
  queryParams.value.endDate = null
  // 重置月份选择
  queryParams.value.trainingMonth = null
  // 重置未订餐筛选条件
  queryParams.value.hasUnordered = null
  isUnorderedFilterActive.value = false
  // 重置分页

  currentPage.value = 1
  pageSize.value = 10
  
  // 重置月度培训数据
  monthlyTrainings.value = []
  
  // 重置选中的培训信息
  queryParams.value.trainingId = null
  selectedTraining.value = null
  
  // 如果对话框打开且是新增模式，清空订餐详情
  if (open.value && !form.value.id) {
    mealDetailData.value = []
  }
  
  handleQuery()
}

function getDeptList() {
  listDept().then(response => {
    // 修改部门列表数据结构，使label为部门名称，value为部门名称（而不是部门ID）
    sys_dept_list.value = response.data.map(item => ({
      label: item.deptName,  // 部门名称作为显示文本
      value: item.deptName   // 部门名称作为值（与后端Employee实体类的dept字段匹配）
    }))
  }).catch(error => {
    console.error("获取部门列表失败:", error)
    proxy.$modal.msgError("获取部门列表失败")
  })
}
function getFormDeptList() {
  listDept().then(response => {
    // 修改表单中的部门选项数据结构
    deptOptions.value = response.data.map(item => ({
      deptId: item.deptId,     // 保留部门ID
      deptName: item.deptName  // 部门名称
    }))
  }).catch(error => {
    console.error("获取部门列表失败:", error)
    proxy.$modal.msgError("获取部门列表失败")
  })
}
/** 查询订餐管理列表 */
function getList() {
  if (!queryParams.value.trainingId) {
    // 如果没有选择培训，清空数据
    processedData.value = []
    paginatedData.value = []
    total.value = 0
    dateColumns.value = []
    return
  }

  loading.value = true
  const params = { ...queryParams.value }

  // 获取所有数据，不进行后端分页
  params.pageNum = 1
  params.pageSize = 10000 // 设置足够大的值获取所有数据

  voList(params).then(response => {
    console.log('订餐列表响应数据:', response)
    orderList.value = response.rows
    total.value = response.total
    loading.value = false

    // 处理数据合并
    processAndMergeData(response.rows, params.hasUnordered)
  }).catch((error) => {
    console.error('获取订餐列表失败:', error)
    loading.value = false
    proxy.$modal.msgError("获取订餐列表失败: " + (error.message || ''))
  })
}


/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加订餐"

  // 设置当前选中的培训信息
  if (queryParams.value.trainingId) {
    const selectedTraining = trainings.value.find(t => t.trainingId == queryParams.value.trainingId)
    if (selectedTraining) {
      form.value.trainingName = selectedTraining.trainingName
      form.value.trainingId = selectedTraining.trainingId
      form.value.trainingDateRange = [selectedTraining.startDate, selectedTraining.endDate]

      // 生成培训期间的订餐详情数据
      generateMealDetailData(selectedTraining.startDate, selectedTraining.endDate)
    }
  } else {
    // 如果没有选择培训，清空订餐详情
    mealDetailData.value = []
  }
}


function generateMealDetailData(startDate, endDate, mealDetails = [], rowData = []) {
  mealDetailData.value = []

  if (!startDate || !endDate) {
    console.log('开始日期或结束日期为空，无法生成订餐详情')
    return
  }

  const start = new Date(startDate)
  const end = new Date(endDate)
  const mealMap = new Map()

  // 将 mealDetails 转换为 Map，便于快速查找
  if (Array.isArray(mealDetails)) {
    mealDetails.forEach(detail => {
      if (!detail.mealDate || !detail.mealType) return
      const key = `${detail.mealDate}_${detail.mealType}`
      // 保存餐食的完整信息，包括ID和状态
      mealMap.set(key, {
        value: detail.isOrdered !== undefined && detail.isOrdered !== null ? 
               String(detail.isOrdered) : null,
        id: detail.id
      })
    })
  }

  let current = new Date(start)
  while (current <= end) {
    const dateStr = formatDate(current)
    const year = current.getFullYear()
    const month = current.getMonth() + 1
    const day = current.getDate()
    const dateLabel = `${year}/${month}/${day}`
    const lunchKey = `${dateStr}_午餐`
    const dinnerKey = `${dateStr}_晚餐`

    // 获取已有的订餐状态和ID
    const lunchData = mealMap.has(lunchKey) ? mealMap.get(lunchKey) : { value: null, id: null }
    const dinnerData = mealMap.has(dinnerKey) ? mealMap.get(dinnerKey) : { value: null, id: null }

    // 确保状态值是字符串类型，以便在下拉框中正确显示
    const formatOrderedValue = (value) => {
      if (value === null || value === undefined) return '3' // 未填写
      return String(value)
    }

    mealDetailData.value.push({
      id: lunchData.id,        // 午餐ID
      dinnerId: dinnerData.id, // 晚餐ID
      date: dateStr,
      dateLabel: dateLabel,
      lunch: formatOrderedValue(lunchData.value),
      dinner: formatOrderedValue(dinnerData.value)
    })

    current.setDate(current.getDate() + 1)
  }

  nextTick(() => {
    console.log("mealDetailData 已更新:", mealDetailData.value)
  })
}
// 修改 handleUpdate 函数中处理部门的部分
function handleUpdate(row) {
  console.log('点击修改按钮', row)
  reset()
  open.value = true
  console.log('对话框已打开', open.value)
  title.value = "修改订餐管理"
  
  // 保存当前的 trainingId，避免在处理过程中被修改
  const currentTrainingId = row.trainingId || queryParams.value.trainingId;
  console.log('当前培训ID:', currentTrainingId)
  // 使用 voList 接口获取该员工在该培训中的所有订餐信息
  const params = {
    trainingId: currentTrainingId,
    employeeNo: row.employeeNo,
    pageSize: 10000 // 获取所有数据
  }

  voList(params).then(response => {
    console.log('=== voList 响应数据 ===')
    console.log('response:', response)

    if (response.rows && response.rows.length > 0) {
      console.log('找到相关订餐数据，数量:', response.rows.length)

      // 使用第一条记录填充基本信息
      const firstRow = response.rows[0]
      form.value = {
        ...firstRow,
        id: firstRow.id,
        empId: firstRow.empId,  // 确保设置empId
        trainingId: currentTrainingId,  // 使用保存的 trainingId
        dept: firstRow.deptName || firstRow.dept  // 处理部门字段，优先使用 deptName
      }

      console.log('填充的基本信息:', form.value)

      // 获取选中的培训信息
      const selectedTraining = trainings.value.find(t => t.trainingId == currentTrainingId)
      if (selectedTraining) {
        console.log('找到选中的培训:', selectedTraining)

        // 合并订餐信息
        const mergedMealDetails = mergeMealDetails(response.rows)

        console.log('=== 合并后的订餐详情 ===')
        console.log('mergedMealDetails:', mergedMealDetails)

        // 生成培训期间的订餐详情数据，并传入已有的订餐信息
        generateMealDetailData(selectedTraining.startDate, selectedTraining.endDate, mergedMealDetails, response.rows)
        
        // 保存原始状态和ID映射关系，用于后续比较
        saveOriginalMealStatus(mergedMealDetails, response.rows);
      }
    } else {
      proxy.$modal.msgError("未找到相关订餐数据")
    }
  }).catch(error => {
    console.error('获取订餐详情失败:', error)
    proxy.$modal.msgError("获取订餐详情失败: " + (error.message || ''))
  })
}
// 保存原始餐食状态，用于后续比较
function saveOriginalMealStatus(mergedMealDetails, rowData) {
  // 初始化原始状态对象
  form.value.originalMealStatus = {};
  
  // 创建日期和ID的映射关系
  form.value.mealIdMap = {};
  
  // 从返回的完整数据中提取每个餐食的ID
  rowData.forEach(row => {
    if (row.mealDetails && Array.isArray(row.mealDetails) && row.mealDetails.length > 0) {
      const detail = row.mealDetails[0]; // 每行数据只有一个mealDetail
      const key = `${detail.mealDate}_${detail.mealType}`;
      // 保存原始值和对应的ID
      form.value.originalMealStatus[key] = detail.isOrdered;
      form.value.mealIdMap[key] = row.id; // 保存该餐食对应的ID
    }
  });
  
  console.log('保存的原始餐食状态:', form.value.originalMealStatus);
  console.log('保存的餐食ID映射:', form.value.mealIdMap);
}

// 合并同一员工同一培训的订餐信息
function mergeMealDetails(rows) {
  const mealArray = []

  rows.forEach(row => {
    if (row.mealDetails && Array.isArray(row.mealDetails)) {
      row.mealDetails.forEach(detail => {
        // 修复：确保 isOrdered 值正确转换为字符串
        mealArray.push({
          ...detail,
          isOrdered: detail.isOrdered !== undefined && detail.isOrdered !== null ? 
                    String(detail.isOrdered) : null
        })
      })
    }
  })
  console.log('合并后的 mealArray:', mealArray)
  return mealArray
}
function getOrderStatusText(status) {
  // 处理 null、undefined 和空字符串的情况
  if (status === null || status === undefined || status === '') {
    return '未填写';
  }
  
  // 处理数字类型
  if (typeof status === 'number') {
    switch (status) {
      case 3: return '未填写'; // 橙色标签 - 未填写
      case 1: return '已订餐'; // 绿色标签 - 已订餐
      case 0: return '不订餐'; // 灰色标签 - 不订餐
      case 2: return '核销';   // 蓝色标签 - 核销
      default: return '未填写';
    }
  }
  
  // 处理字符串类型
  if (typeof status === 'string') {
    switch (status) {
      case '3': return '未填写'; // 橙色标签 - 未填写
      case '1': return '已订餐'; // 绿色标签 - 已订餐
      case '0': return '不订餐'; // 灰色标签 - 不订餐
      case '2': return '核销';   // 蓝色标签 - 核销
      default: return '未填写';
    }
  }
  
  // 默认情况
  return '未填写';
}

function getOrderStatusType(status) {
  // 处理 null、undefined 和空字符串的情况
  if (status === null || status === undefined || status === '') {
    return 'warning'; // 橙色标签
  }
  
  // 处理数字类型
  if (typeof status === 'number') {
    switch (status) {
      case 3: return 'warning'; // 橙色标签 - 未填写
      case 1: return 'success'; // 绿色标签 - 已订餐
      case 0: return 'info';    // 灰色标签 - 不订餐
      case 2: return 'primary'; // 蓝色标签 - 核销
      default: return 'warning';
    }
  }
  
  // 处理字符串类型
  if (typeof status === 'string') {
    switch (status) {
      case '3': return 'warning'; // 橙色标签 - 未填写
      case '1': return 'success'; // 绿色标签 - 已订餐
      case '0': return 'info';    // 灰色标签 - 不订餐
      case '2': return 'primary'; // 蓝色标签 - 核销
      default: return 'warning';
    }
  }
  
  // 默认情况
  return 'warning';
}




function formatDate(date) {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}



// 修改 submitForm 函数中处理部门的部分
function submitForm() {
  proxy.$refs["orderRef"].validate(valid => {
    if (valid) {
      const formData = { ...form.value }
      console.log('=== 开始提交表单 ===');
      console.log('表单原始数据:', formData);

      // 确保设置培训ID - 优先使用表单中的 trainingId
      if (formData.trainingId) {
        // 如果表单中已有 trainingId，确保它是数字类型
        formData.trainingId = parseInt(formData.trainingId);
      } else if (selectedTrainingId.value) {
        // 否则使用 selectedTrainingId
        formData.trainingId = parseInt(selectedTrainingId.value);
      }

      console.log('提交时使用的 trainingId:', formData.trainingId);

      // 构造订餐详情数据
      const mealDetails = []
      mealDetailData.value.forEach(item => {
        mealDetails.push({
          id: item.id, // 午餐ID
          mealDate: item.date,
          mealType: '午餐',
          isOrdered: item.lunch
        })
        mealDetails.push({
          id: item.dinnerId, // 晚餐ID
          mealDate: item.date,
          mealType: '晚餐',
          isOrdered: item.dinner
        })
      })

      formData.mealDetails = mealDetails
      console.log('提交的 mealDetails:', mealDetails);

      // 验证必要字段
      if (!formData.trainingId) {
        proxy.$modal.msgError("培训信息不完整，请重新选择培训")
        return
      }

      // 新增时只验证员工姓名和手机号，修改时还需验证部门和邮箱
      if (!formData.employeeName || !formData.phone) {
        proxy.$modal.msgError("请填写员工姓名和手机号")
        return
      }

      // 修改时需要验证部门
      if (formData.id != null && !formData.dept) {
        proxy.$modal.msgError("请填写部门")
        return
      }
       // 修改时需要验证部门和邮箱
      if (formData.id != null &&  !formData.email) {
        proxy.$modal.msgError("请填写邮箱")
        return
      }


      // 根据是新增还是修改采用不同的处理逻辑
      if (formData.id != null) {
        // 修改操作 - 使用新接口更新发生变化的订餐状态
        if (!formData.empId) {
          proxy.$modal.msgError("员工ID不能为空")
          return
        }

        // 确保部门字段正确处理
        if (formData.deptName) {
          formData.dept = formData.deptName;
        }

        console.log('=== 准备更新订单状态 ===');
        // 只更新发生变化的餐食状态，传入ID映射关系
        updateChangedOrderStatuses(formData.mealIdMap, mealDetails, formData.originalMealStatus).then(() => {
          console.log('=== 所有更新请求完成 ===');
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        }).catch(error => {
          console.error('修改订餐信息失败:', error)
          proxy.$modal.msgError("修改失败: " + (error.message || '未知错误'))
        })
      } else {
        // ... existing code for new order ...
      }
    }
  })
}

// 修改 updateChangedOrderStatuses 函数，增加更多调试信息
function updateChangedOrderStatuses(mealIdMap, mealDetails, originalMealStatus) {
  console.log('=== 开始检查需要更新的餐食状态 ===');
  console.log('餐食ID映射:', mealIdMap);
  console.log('餐食详情数量:', mealDetails.length);
  console.log('餐食详情:', mealDetails);
  console.log('原始状态:', originalMealStatus);
  
  // 创建更新状态的Promise数组
  const updatePromises = [];
  
  mealDetails.forEach(detail => {
    // 构造唯一键
    const key = `${detail.mealDate}_${detail.mealType}`;
    const originalStatus = originalMealStatus ? originalMealStatus[key] : null;
    
    // 确保比较的是相同类型
    const currentStatus = detail.isOrdered;
    const originalStatusStr = originalStatus !== null && originalStatus !== undefined ? String(originalStatus) : '3'; // 默认未填写
    const currentStatusStr = currentStatus !== null && currentStatus !== undefined ? String(currentStatus) : '3'; // 默认未填写
    
    // 比较原始状态和当前状态
    const hasChanged = originalStatusStr !== currentStatusStr;
    
    console.log(`检查餐食状态变化: ${key}`);
    console.log(`  原始状态: ${originalStatusStr} (原值: ${originalStatus})`);
    console.log(`  当前状态: ${currentStatusStr} (原值: ${currentStatus})`);
    console.log(`  是否变化: ${hasChanged}`);
    
    // 只有状态发生变化才添加到更新列表
    if (hasChanged) {
      // 从映射关系中获取实际的餐食ID
      const mealId = mealIdMap[key];
      if (mealId) {
        console.log(`准备发送更新请求: id=${mealId}, status=${currentStatusStr}, mealDate=${detail.mealDate}, mealType=${detail.mealType}`);
        updatePromises.push(alterMealStatus(mealId, currentStatusStr));
      } else {
        console.warn(`未找到餐食ID映射: ${key}`);
      }
    }
  });

  console.log(`总共需要发送 ${updatePromises.length} 个请求`);
  console.log('=== 检查完成 ===');
  
  // 等待所有更新完成
  return Promise.all(updatePromises);
}
// 新增函数：使用新接口更新订餐状态
function updateOrderStatuses(id, mealDetails) {
  // 创建更新状态的Promise数组
  const updatePromises = mealDetails.map(detail => {
    // 只有当状态有效时才调用接口更新
    if (detail.isOrdered !== undefined && detail.isOrdered !== null) {
      return alterMealStatus(id, detail.isOrdered);
    }
    return Promise.resolve();
  });

  // 过滤掉无效的Promise
  const validPromises = updatePromises.filter(promise => promise !== undefined);

  // 等待所有更新完成
  return Promise.all(validPromises);
}


const isMultipleSelect = ref(true) // 表示是否是多选状态
const hasNoSelection = ref(true)   // 表示是否没有选择任何项


/** 删除按钮操作 */
// ... existing code ...
function handleDelete1(row) {
  console.log('=== 删除操作开始 ===');
  console.log('传入的行数据:', row);
  console.log('ids.value:', ids.value);
  console.log('selectedTrainingId.value:', selectedTrainingId.value);
  console.log('queryParams.value.trainingId:', queryParams.value.trainingId);

  // 确定有效的培训ID
  const effectiveTrainingId = queryParams.value.trainingId || (selectedTrainingId.value ? parseInt(selectedTrainingId.value) : null);
  console.log('有效的培训ID:', effectiveTrainingId);

  if (row) {
    // 单条记录删除（表格行中的删除按钮）
    console.log('执行单条记录删除');
    console.log('row.id:', row.id, '类型:', typeof row.id);
    console.log('row.empId:', row.empId, '类型:', typeof row.empId);
    console.log('row.trainingId:', row.trainingId, '类型:', typeof row.trainingId);
    // 检查必要字段是否存在
    if (!row.empId) {
      proxy.$modal.msgError("无法获取员工信息，请刷新页面后重试");
      console.error("删除失败：缺少员工ID", row);
      return;
    }
    // 确定有效的培训ID
    const rowTrainingId = row.trainingId || effectiveTrainingId;
    console.log('行数据中的培训ID:', rowTrainingId);

    // 修复：将isSingleDelete的定义移到使用之前
    const isSingleDelete = row.empId && rowTrainingId;
    console.log('是否可以单条删除:', isSingleDelete);
    if (!rowTrainingId) {
      proxy.$modal.msgError("无法获取培训信息，请刷新页面后重试");
      console.error("删除失败：缺少培训ID", row);
      return;
    }
// Deleted:    const isSingleDelete = row.empId && rowTrainingId;
// Deleted:    console.log('是否可以单条删除:', isSingleDelete);
    if (!isSingleDelete) {
      proxy.$modal.msgError("无法获取必要的删除信息（员工ID或培训ID缺失）");
      return;
    }

    const deleteInfo = `员工"${row.employeeName}"在培训"${row.trainingName}"中的所有订餐信息`;
    console.log('准备显示删除确认信息:', deleteInfo);

    proxy.$modal.confirm('是否确认删除 ' + deleteInfo + ' ？').then(function () {
      console.log('用户确认删除单条记录');
      console.log('参数 empId:', row.empId, 'trainingId:', rowTrainingId);
      // 确保参数是数字类型
      return delOrdersByEmpAndTraining(parseInt(row.empId), parseInt(rowTrainingId));
    }).then((response) => {
      console.log('=== 单条删除操作成功 ===', response);
      getList();
      proxy.$modal.msgSuccess("删除成功");
    }).then((response) => {
      console.log('=== 单条删除操作成功 ===', response);
      getList();
      proxy.$modal.msgSuccess("删除成功");
    }).catch((error) => {
      console.log('=== 单条删除操作被拒绝或失败 ===', error);
      if (error !== "未选择数据") {
        console.error("删除失败:", error);
        proxy.$modal.msgError("删除失败: " + (error.message || error));
      }
    });
  } else {
    // 批量删除（工具栏中的删除按钮）
    console.log('执行批量删除');
    if (!ids || !ids.value || ids.value.length === 0) {
      proxy.$modal.msgError("请至少选择一条数据");
      return;
    }

    // 通过ID查找对应的行数据，获取员工ID列表
    const selectedRows = processedData.value.filter(item => ids.value.includes(item.id));
    console.log('选中的行数据:', selectedRows);

    if (selectedRows.length === 0) {
      proxy.$modal.msgError("未找到选中的数据");
      return;
    }

    // 检查是否所有选中行都有员工ID和培训ID
    const validRows = selectedRows.filter(item => item.empId && effectiveTrainingId);
    if (validRows.length !== selectedRows.length) {
      proxy.$modal.msgError("部分选中数据缺少必要的删除信息（员工ID或培训ID）");
      return;
    }

    // 构建删除信息
    const employeeNames = validRows.map(item => item.employeeName).join(', ');
    const deleteInfo = `${validRows.length}名员工在当前培训中的所有订餐信息`;
    console.log('准备显示批量删除确认信息:', deleteInfo);

    proxy.$modal.confirm('是否确认删除 ' + deleteInfo + ' ？').then(function () {
      console.log('用户确认批量删除');

      // 逐个删除每个员工在当前培训中的所有订餐信息
      const deletePromises = validRows.map(row => {
        console.log('删除员工:', row.empId, '在培训:', effectiveTrainingId, '中的订餐信息');
        return delOrdersByEmpAndTraining(parseInt(row.empId), parseInt(effectiveTrainingId));
      });

      // 等待所有删除操作完成
      return Promise.all(deletePromises);
    }).then((responses) => {
      console.log('=== 批量删除操作成功 ===', responses);
      getList();
      proxy.$modal.msgSuccess("删除成功");
    }).catch((error) => {
      console.log('=== 批量删除操作被拒绝或失败 ===', error);
      if (error !== "未选择数据") {
        console.error("删除失败:", error);
        proxy.$modal.msgError("删除失败: " + (error.message || error));
      }
    });
  }
}

function handleDelete(row) {
  console.log('=== 删除操作开始 ===');
  console.log('传入的行数据:', row);
  console.log('ids.value:', ids.value);
  console.log('selectedTrainingId.value:', selectedTrainingId.value);
  console.log('queryParams.value.trainingId:', queryParams.value.trainingId);

  // 确定有效的培训ID
  const effectiveTrainingId = queryParams.value.trainingId || (selectedTrainingId.value ? parseInt(selectedTrainingId.value) : null);
  console.log('有效的培训ID:', effectiveTrainingId);

  if (row) {
    // 单条记录删除（表格行中的删除按钮）
    console.log('执行单条记录删除');
    console.log('row.id:', row.id, '类型:', typeof row.id);
    console.log('row.empId:', row.empId, '类型:', typeof row.empId);
    console.log('row.trainingId:', row.trainingId, '类型:', typeof row.trainingId);
    
    // 检查必要字段是否存在
    if (!row.empId) {
      proxy.$modal.msgError("无法获取员工信息，请刷新页面后重试");
      console.error("删除失败：缺少员工ID", row);
      return;
    }
    
    // 确定有效的培训ID
    const rowTrainingId = row.trainingId || effectiveTrainingId;
    console.log('行数据中的培训ID:', rowTrainingId);

    const isSingleDelete = row.empId && rowTrainingId;
    console.log('是否可以单条删除:', isSingleDelete);
    
    if (!rowTrainingId) {
      proxy.$modal.msgError("无法获取培训信息，请刷新页面后重试");
      console.error("删除失败：缺少培训ID", row);
      return;
    }

    if (!isSingleDelete) {
      proxy.$modal.msgError("无法获取必要的删除信息（员工ID或培训ID缺失）");
      return;
    }

    const deleteInfo = `员工"${row.employeeName}"在培训"${row.trainingName}"中的所有订餐信息`;
    console.log('准备显示删除确认信息:', deleteInfo);

    proxy.$modal.confirm('是否确认删除 ' + deleteInfo + ' ？').then(function () {
      console.log('用户确认删除单条记录');
      console.log('参数 empId:', row.empId, 'trainingId:', rowTrainingId);
      // 确保参数是数字类型
      return delOrdersByEmpAndTraining(parseInt(row.empId), parseInt(rowTrainingId));
    }).then((response) => {
      console.log('=== 单条删除操作成功 ===', response);
      if (response.code === 200) {
        proxy.$modal.msgSuccess("删除成功");
        
        // 更新前端显示数据
        // 单条删除：从 processedData 和 paginatedData 中移除该条记录
        const rowIndex = processedData.value.findIndex(item => item.id === row.id);
        if (rowIndex > -1) {
          processedData.value.splice(rowIndex, 1);
        }
        
        const pageRowIndex = paginatedData.value.findIndex(item => item.id === row.id);
        if (pageRowIndex > -1) {
          paginatedData.value.splice(pageRowIndex, 1);
        }
        
        // 更新总数
        total.value = processedData.value.length;
        
        // 重新应用分页
        applyFrontendPagination();
        
        // 更新选择状态
        const selectedIndex = ids.value.indexOf(row.id);
        if (selectedIndex > -1) {
          ids.value.splice(selectedIndex, 1);
        }
        single.value = ids.value.length !== 1;
        isMultipleSelect.value = ids.value.length > 1;
        hasNoSelection.value = ids.value.length === 0;
      } else {
        proxy.$modal.msgError("删除失败: " + response.msg);
      }
    }).catch((error) => {
      console.log('=== 单条删除操作被拒绝或失败 ===', error);
      if (error !== "未选择数据") {
        console.error("删除失败:", error);
        proxy.$modal.msgError("删除失败: " + (error.message || error));
      }
    });
  } else {
    // 批量删除（工具栏中的删除按钮）
    console.log('执行批量删除');
    if (!ids || !ids.value || ids.value.length === 0) {
      proxy.$modal.msgError("请至少选择一条数据");
      return;
    }

    // 通过ID查找对应的行数据，获取员工ID列表
    const selectedRows = processedData.value.filter(item => ids.value.includes(item.id));
    console.log('选中的行数据:', selectedRows);

    if (selectedRows.length === 0) {
      proxy.$modal.msgError("未找到选中的数据");
      return;
    }

    // 检查是否所有选中行都有员工ID和培训ID
    const validRows = selectedRows.filter(item => item.empId && effectiveTrainingId);
    if (validRows.length !== selectedRows.length) {
      proxy.$modal.msgError("部分选中数据缺少必要的删除信息（员工ID或培训ID）");
      return;
    }

    // 构建删除信息
    const employeeNames = validRows.map(item => item.employeeName).join(', ');
    const deleteInfo = `${validRows.length}名员工在当前培训中的所有订餐信息`;
    console.log('准备显示批量删除确认信息:', deleteInfo);

    proxy.$modal.confirm('是否确认删除 ' + deleteInfo + ' ？').then(function () {
      console.log('用户确认批量删除');

      // 逐个删除每个员工在当前培训中的所有订餐信息
      const deletePromises = validRows.map(row => {
        console.log('删除员工:', row.empId, '在培训:', effectiveTrainingId, '中的订餐信息');
        return delOrdersByEmpAndTraining(parseInt(row.empId), parseInt(effectiveTrainingId));
      });

      // 等待所有删除操作完成
      return Promise.all(deletePromises);
    }).then((responses) => {
      console.log('=== 批量删除操作成功 ===', responses);
      proxy.$modal.msgSuccess("删除成功");
      
      // 更新前端显示数据
      // 批量删除：从 processedData 和 paginatedData 中移除所有被删除的记录
      processedData.value = processedData.value.filter(item => !ids.value.includes(item.id));
      paginatedData.value = paginatedData.value.filter(item => !ids.value.includes(item.id));
      
      // 更新总数
      total.value = processedData.value.length;
      
      // 重新应用分页
      applyFrontendPagination();
      
      // 更新选择状态
      ids.value = [];
      single.value = true;
      isMultipleSelect.value = false;
      hasNoSelection.value = true;
    }).catch((error) => {
      console.log('=== 批量删除操作被拒绝或失败 ===', error);
      if (error !== "未选择数据") {
        console.error("删除失败:", error);
        proxy.$modal.msgError("删除失败: " + (error.message || error));
      }
    });
  }
}


/** 导出按钮操作 */
function handleExport() {
  proxy.$modal.confirm('是否确认导出订餐管理数据？').then(() => {
    const exportParams = { ...queryParams.value };
    delete exportParams.id;

    return exportOrder(exportParams);
  }).then(response => {
    const blob = new Blob([response]);
    const link = document.createElement('a');
    const fileName = `order_${new Date().getTime()}.xlsx`;

    link.href = URL.createObjectURL(blob);
    link.download = fileName;
    link.click();
    URL.revokeObjectURL(link.href);
  }).catch(() => {
    // 可选处理取消或错误
  });
}
// ... existing code ...
// 在其他方法后面添加以下导入相关方法

// 导入按钮点击事件
function handleImport() {
  upload.title = "订餐数据导入"
  upload.open = true
}

// 下载导入模板
function importTemplate() {
  try {
    // 直接从public目录下载订餐表模板.xlsx
    const link = document.createElement('a');
    link.href = '/订餐表模板.xlsx';
    link.download = '订餐表模板.xlsx';
    link.click();
  } catch (error) {
    proxy.$modal.msgError("模板下载失败");
  }
}

// 文件上传进度处理
function handleFileUploadProgress() {
  upload.isUploading = true
}

// 在文件上传成功处理中重置表单
function handleFileSuccess(response) {
  upload.open = false;
  upload.isUploading = false;
  proxy.$refs.uploadRef?.handleRemove();
  proxy.$alert(`<div style="overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;">${response.msg}</div>`, "导入结果", { dangerouslyUseHTMLString: true });
  getList();
}


function validateEmployeeOnBlur() {
  // 只在新增时进行验证
  if (!form.value.id && form.value.employeeName && form.value.phone) {
    // 添加防抖，避免频繁调用接口
    clearTimeout(validateEmployeeOnBlur.timer);
    validateEmployeeOnBlur.timer = setTimeout(() => {
      validateEmployee({
        employeeName: form.value.employeeName,
        phone: form.value.phone
      }).then(response => {
        if (response.code === 200) {
          if (response.data && response.data.nameMismatch) {
            // 显示姓名不匹配警告
            proxy.$modal.msgWarning(response.data.message);
          }
        } else {
          // 显示错误信息
          proxy.$modal.msgError(response.msg);
        }
      }).catch(error => {
        console.error('验证员工信息失败:', error);
      });
    }, 500); // 500ms 防抖
  }
}
// 提交文件表单
function submitFileForm() {
  if (!selectedTraining.value) {
    proxy.$modal.msgError("请选择一个培训项目");
    return;
  }

  // 获取上传的文件
  let file = null;
  const fileInput = proxy.$refs.uploadRef.$el.querySelector('input[type="file"]');
  
  // 检查通过文件选择器选择的文件
  if (fileInput && fileInput.files && fileInput.files.length > 0) {
    file = fileInput.files[0];
  }
  
  // 如果通过文件选择器没找到文件，尝试从uploadRef的uploadFiles中获取（拖拽的文件）
  if (!file && proxy.$refs.uploadRef.uploadFiles && proxy.$refs.uploadRef.uploadFiles.length > 0) {
    const uploadedFile = proxy.$refs.uploadRef.uploadFiles[0];
    if (uploadedFile && uploadedFile.raw) {
      file = uploadedFile.raw;
    } else if (uploadedFile && uploadedFile.response) {
      // 如果文件已经上传过，可能在response中
      file = uploadedFile.response;
    }
  }

  // 如果还是没有文件，则报错
  if (!file) {
    proxy.$modal.msgError("请选择要导入的文件");
    return;
  }

  const formData = new FormData();
  formData.append('file', file);
  
  // 添加参数
  formData.append('trainingName', selectedTraining.value.trainingName);
  formData.append('startDate', selectedTraining.value.startDate);
  formData.append('endDate', selectedTraining.value.endDate);
  formData.append('updateSupport', upload.updateSupport);

  // 手动上传文件
  upload.isUploading = true;
  importMealOrderTable(formData).then(response => {
    handleFileSuccess(response);
  }).catch(error => {
    upload.isUploading = false;
    // 修改为弹窗模式显示错误信息
    proxy.$alert(`导入失败: ${error.message || "未知错误"}`, '导入结果', {
      confirmButtonText: '确定',
      type: 'error',
      dangerouslyUseHTMLString: true,
      callback: () => {
        // 点击确定后的回调，这里可以留空或添加其他逻辑
      }
    });
  });
}


// 修改 processAndMergeData 函数中处理部门的部分
function processAndMergeData(rawData, hasUnordered = null) {
  console.log('=== 开始处理合并数据 ===');
  console.log('函数开始时 selectedTrainingId.value:', selectedTrainingId.value);
  console.log('原始数据:', rawData);
  console.log('未订餐筛选条件:', hasUnordered);

  console.log('selectedTrainingId.value:', selectedTrainingId.value);
  console.log('queryParams.value.trainingId:', queryParams.value.trainingId);

  // 确定有效的培训ID
  const effectiveTrainingId = queryParams.value.trainingId || (selectedTrainingId.value ? parseInt(selectedTrainingId.value) : null);
  console.log('有效的培训ID:', effectiveTrainingId);
  if (!rawData || rawData.length === 0) {
    console.log('数据为空，清空处理后数据');
    processedData.value = []
    paginatedData.value = []
    total.value = 0
    dateColumns.value = []
    return Promise.resolve()
  }

  // 用Map来合并相同员工相同培训的数据
  const mergeMap = new Map()

  // 收集所有用餐日期
  const allMealDates = new Set()

  rawData.forEach((item, index) => {
    console.log(`处理第${index}项数据:`, item);
    // 确保 mealDetails 存在
    if (!item.mealDetails) {
      item.mealDetails = []
    }
    // 确保trainingId存在（从查询参数中获取）
    if (!item.trainingId && effectiveTrainingId) {
      item.trainingId = effectiveTrainingId;
    }
    // 创建唯一标识：培训名称+员工编号+培训开始结束日期
    const uniqueKey = `${item.trainingName || '未命名培训'}_${item.employeeNo}_${item.startDate}_${item.endDate}`

    // 收集用餐日期
    if (item.mealDetails && Array.isArray(item.mealDetails)) {
      item.mealDetails.forEach((detail, detailIndex) => {
        if (detail.mealDate) {
          allMealDates.add(detail.mealDate)
        }
      })
    }

    // 如果还没有这个员工的培训记录，则创建
    if (!mergeMap.has(uniqueKey)) {
      const recordToStore = {
        ...item,
        trainingName: item.trainingName || '未命名培训',
        meals: {}, // 用于存储用餐信息
        // 确保关键字段不丢失
        id: item.id,
        empId: item.empId,
        trainingId: item.trainingId,
        employeeName: item.employeeName,
        employeeNo: item.employeeNo,
        dept: item.deptName || item.dept  // 处理部门字段，优先使用 deptName
      };
      mergeMap.set(uniqueKey, recordToStore);
    }

    // 获取已存在的记录
    const existingRecord = mergeMap.get(uniqueKey)

    // 合并用餐详情 - 保持原始 isOrdered 值
    if (item.mealDetails && Array.isArray(item.mealDetails)) {
      item.mealDetails.forEach(detail => {
        const mealKey = `${detail.mealDate}_${detail.mealType}`
        // 直接使用原始的 isOrdered 值，不做转换
        existingRecord.meals[mealKey] = detail.isOrdered
      })
    }
  })

  // 转换Map为数组
  let mergedArray = Array.from(mergeMap.values())
  console.log('合并后的数组:', mergedArray);

  // 如果需要筛选未订餐的员工
  if (hasUnordered === '0') {
    // 获取培训的开始和结束日期
    const trainingStartDate = selectedTraining.value?.startDate;
    const trainingEndDate = selectedTraining.value?.endDate;

    if (trainingStartDate && trainingEndDate) {
      // 生成培训期间的所有日期
      const trainingDates = [];
      const startDate = new Date(trainingStartDate);
      const endDate = new Date(trainingEndDate);
      const currentDate = new Date(startDate);

      while (currentDate <= endDate) {
        trainingDates.push(formatDateForCompare(currentDate));
        currentDate.setDate(currentDate.getDate() + 1);
      }

      console.log('培训期间所有日期:', trainingDates);

      // 筛选出有未订餐记录的员工 (isOrdered 为 3 或 null/undefined 表示未填写)
      mergedArray = mergedArray.filter(record => {
        // 检查是否在培训期间有任何一天未填写订餐
        return trainingDates.some(date => {
          const lunchKey = `${date}_午餐`;
          const dinnerKey = `${date}_晚餐`;

          const lunchOrdered = record.meals[lunchKey];
          const dinnerOrdered = record.meals[dinnerKey];
          
          // 检查是否未填写 (状态为 3 或 null/undefined)
          return (lunchOrdered === 3 || lunchOrdered === '3' || lunchOrdered === null || lunchOrdered === undefined) ||
                 (dinnerOrdered === 3 || dinnerOrdered === '3' || dinnerOrdered === null || dinnerOrdered === undefined);
        });
      });

      console.log('筛选出有未订餐情况的员工:', mergedArray);
    }
  } else if (hasUnordered === '1') {
    // 筛选完全订餐的员工（培训期间每天午餐和晚餐都订餐）
    const trainingStartDate = selectedTraining.value?.startDate;
    const trainingEndDate = selectedTraining.value?.endDate;

    if (trainingStartDate && trainingEndDate) {
      // 生成培训期间的所有日期
      const trainingDates = [];
      const startDate = new Date(trainingStartDate);
      const endDate = new Date(trainingEndDate);
      const currentDate = new Date(startDate);

      while (currentDate <= endDate) {
        trainingDates.push(formatDateForCompare(currentDate));
        currentDate.setDate(currentDate.getDate() + 1);
      }

      console.log('培训期间所有日期:', trainingDates);

      // 筛选出完全订餐的员工 (isOrdered 为 1 表示已订餐)
      mergedArray = mergedArray.filter(record => {
        // 检查是否在培训期间每天都订餐了（午餐和晚餐都订餐）
        return trainingDates.every(date => {
          const lunchKey = `${date}_午餐`;
          const dinnerKey = `${date}_晚餐`;

          const lunchOrdered = record.meals[lunchKey];
          const dinnerOrdered = record.meals[dinnerKey];
          
          // 只有当午餐和晚餐都已订餐时才算完全订餐
          return (lunchOrdered === 1 || lunchOrdered === '1') && (dinnerOrdered === 1 || dinnerOrdered === '1');
        });
      });

      console.log('筛选出完全订餐的员工:', mergedArray);
    }
  }

  // 生成动态列信息
  const sortedDates = Array.from(allMealDates).sort()

  // 修复：使用反应式方式更新dateColumns
  dateColumns.value = sortedDates.map(date => {
    const dateObj = new Date(date)
    const year = dateObj.getFullYear()
    const month = String(dateObj.getMonth() + 1).padStart(2, '0')
    const day = String(dateObj.getDate()).padStart(2, '0')
    const dateKey = date.replace(/-/g, '')

    return {
      date: date,
      label: `${year}/${month}/${day}`,
      lunchProp: `lunch_${dateKey}`,
      dinnerProp: `dinner_${dateKey}`
    }
  })

  // 为每条记录添加动态列数据
  const finalData = mergedArray.map((record, index) => {
    // 先复制原记录，确保保留关键字段
    const finalRecord = {
      ...record,
      id: record.id,
      empId: record.empId,
      trainingId: record.trainingId,
      employeeName: record.employeeName,
      employeeNo: record.employeeNo,
      trainingName: record.trainingName,
      dept: record.deptName || record.dept  // 处理部门字段，优先使用 deptName
    }

    // 初始化所有动态列为未填写状态(3)
    dateColumns.value.forEach(col => {
      finalRecord[col.lunchProp] = 3  // 默认为未填写
      finalRecord[col.dinnerProp] = 3 // 默认为未填写
    })

    // 根据实际订餐情况更新值
    Object.keys(record.meals).forEach(mealKey => {
      const [date, mealType] = mealKey.split('_')
      const dateKey = date.replace(/-/g, '')
      const isOrdered = record.meals[mealKey]

      if (mealType === '午餐') {
        finalRecord[`lunch_${dateKey}`] = isOrdered !== undefined && isOrdered !== null ? isOrdered : 3
      } else if (mealType === '晚餐') {
        finalRecord[`dinner_${dateKey}`] = isOrdered !== undefined && isOrdered !== null ? isOrdered : 3
      }
    })

    // 删除临时属性，但保留关键字段
    delete finalRecord.meals
    delete finalRecord.mealDetails

    console.log(`最终第${index}条记录:`, finalRecord);
    return finalRecord
  })

  // 保存处理后的数据
  processedData.value = finalData
  total.value = finalData.length
  console.log('处理完成的最终数据:', finalData);

  // 应用前端分页
  nextTick(() => {
    applyFrontendPagination()
  })

  return Promise.resolve()
}
// 添加数据处理和合并函数

// 添加日期格式化函数
function formatDateForCompare(date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}
// 添加前端分页函数
function applyFrontendPagination() {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  paginatedData.value = processedData.value.slice(start, end)
}

// 添加分页处理函数
function handlePagination({ page, limit }) {
  currentPage.value = page
  pageSize.value = limit
  applyFrontendPagination()
}

// 保存文件的通用方法
function saveAs(response, fileName) {
  const blob = new Blob([response])
  const link = document.createElement('a')
  link.href = URL.createObjectURL(blob)
  link.download = fileName
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

// 处理多选
function handleSelectionChange(selection) {
  if (selection) {
    ids.value = selection.map(item => item.id)
    single.value = selection.length !== 1
    isMultipleSelect.value = selection.length > 1
    hasNoSelection.value = false
  } else {
    ids.value = []
    single.value = true
    isMultipleSelect.value = false
    hasNoSelection.value = true
  }
}
getDeptList()     // 用于查询条件的部门列表
getFormDeptList() // 用于表单的部门列表
getList()

// 修改页面加载时的逻辑
onMounted(() => {
  getTrainings().then(() => {
    // 确保在获取培训列表后再获取部门列表和订餐列表
    getDeptList();
    getFormDeptList();
    // getList(); // 这个会在 handleQuery 中被调用
  });
});
</script>
<style scoped>
.training-list-container {
  border: 2px solid #e5e5e5;
  border-radius: 8px;
  padding: 16px;
  background-color: #f9f9f9;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.training-search {
  margin-bottom: 16px;
}

.training-list {
  border: 1px solid #ddd;
  border-radius: 4px;
  background-color: white;
  overflow: hidden;
}

.training-menu {
  background-color: transparent;
  border: none;
}

.training-menu .el-menu-item {
  padding: 12px 16px;
  font-size: 15px;
  /* 字体大小 */
  color: #333;
  transition: all 0.2s ease;
  border-bottom: 1px solid #eee;
  /* 添加底部分隔线 */
}

.training-menu .el-menu-item:last-child {
  border-bottom: none;
  /* 最后一个项目不显示分隔线 */
}

.training-menu .el-menu-item:hover {
  background-color: #f5f5f5;
  color: #1890ff;
}

.training-menu .el-menu-item.is-active {
  background-color: #1890ff;
  color: white;
}

.training-info-card {
  margin-bottom: 15px;
}

/* 确保培训信息区域正常显示 */
.el-card__body {
  padding: 15px;
}

.training-info-card .el-row {
  line-height: 1.8;
}

.header-title {
  font-size: 20px;

}

/* 表格自适应相关样式 */
.adaptive-table {
  width: 100%;
  max-height: calc(100vh - 300px);
}


.training-menu .el-menu-item.is-active {
  background-color: #1890ff;
  color: white;
}

.training-checkbox {
  margin-right: 8px;
}

.training-index {
  margin-right: 8px;
  color: #999;
  font-size: 14px;
}

.training-name {
  flex: 1;
}

.training-info-card {
  margin-bottom: 15px;
}

/* 确保培训信息区域正常显示 */
.el-card__body {
  padding: 15px;
}

.training-info-card .el-row {
  line-height: 1.8;
}

/* 表格自适应相关样式 */
.adaptive-table {
  width: 100%;
  max-height: calc(100vh - 300px);
}

.training-summary .el-tag {
  font-weight: bold;
  font-size: 14px;
  padding: 8px 16px;
  --el-tag-bg-color: #f0f2f5;
  --el-tag-border-color: #dcdfe6;
  --el-tag-text-color: #606266;
  width: 100%;
  justify-content: right;
}

.training-summary {
  margin-bottom: 10px;
  text-align: center;
  font-weight: bold;
  color: #666;
}
.text-truncate {
  overflow: visible;
  text-overflow: clip;
  white-space: normal;
}
</style>